using Acme.BookStore.Domain.Entities;
using Acme.BookStore.Purchase.Customergoods;
using Acme.BookStore.PurchaseDto.Goods;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Acme.BookStore.Purchase.Goods
{

    [RemoteService]
    public class GoodsAppService : ApplicationService, IGoodsAppService
    {
        private readonly IRepository<GoodsModel, Guid> _goodsRepository;

        public GoodsAppService(IRepository<GoodsModel, Guid> goodsRepository)
        {
            _goodsRepository = goodsRepository;
        }

        public async Task<PagedResultDto<GoodsDto>> GetListAsync(GetGoodsListInput input)
        {
            var queryable = await _goodsRepository.GetQueryableAsync();

            var query = queryable
                .WhereIf(!string.IsNullOrWhiteSpace(input.Sku), x => x.Sku.Contains(input.Sku))
                .WhereIf(!string.IsNullOrWhiteSpace(input.ProductName), x => x.ProductName.Contains(input.ProductName))
                .WhereIf(!string.IsNullOrWhiteSpace(input.Barcode), x => x.Barcode.Contains(input.Barcode))
                .WhereIf(!string.IsNullOrWhiteSpace(input.Specification), x => x.Specification.Contains(input.Specification))
                .WhereIf(!string.IsNullOrWhiteSpace(input.Brand), x => x.Brand.Contains(input.Brand));

            var totalCount = await AsyncExecuter.CountAsync(query);

            var goods = await AsyncExecuter.ToListAsync(
                query.PageBy(input).OrderBy(input.Sorting ?? nameof(GoodsModel.Id))
            );

            return new PagedResultDto<GoodsDto>(
                totalCount,
                ObjectMapper.Map<List<GoodsModel>, List<GoodsDto>>(goods)
            );
        }
    }
} 